package com.itheima.easy.face.impl;

import com.itheima.easy.adapter.CommonPayAdapter;
import com.itheima.easy.constant.TradingCacheConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.face.CommonPayFace;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.vo.RefundRecordVo;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName CommonPayFaceImpl.java
 * @Description 基础交易face接口实现
 */
@Component
@Slf4j
public class CommonPayFaceImpl implements CommonPayFace {

    @Autowired
    CommonPayAdapter commonPayAdapter;

    @Autowired
    RedissonClient redissonClient;

    public String queryQrCode(TradingVo tradingVo) {
        return commonPayAdapter.queryQrCode(tradingVo);
    }

    @Transactional
    public TradingVo queryTrading(TradingVo tradingVo) throws ProjectException {
        return commonPayAdapter.queryTrading(tradingVo);
    }

    /**
     * 申请退款
     * @param tradingVo 交易单
     * @return
     * @throws ProjectException
     */
    @Transactional
    public TradingVo refundTrading(TradingVo tradingVo) throws ProjectException {
        //1、对交易订单加锁
        Long productOrderNo = tradingVo.getProductOrderNo();
        String key = TradingCacheConstant.REFUND_PAY + productOrderNo;
        RLock lock = redissonClient.getFairLock(key);
        try {
            boolean flag = lock.tryLock(TradingCacheConstant.REDIS_WAIT_TIME, TimeUnit.SECONDS);
            if (flag){
                return commonPayAdapter.refundTrading(tradingVo);
            }else {
                throw new ProjectException(TradingEnum.TRAD_REFUND_FAIL);
            }
        } catch (Exception e) {
            log.error("统一收单交易退款接口异常:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradingEnum.TRAD_REFUND_FAIL);
        }finally {
            lock.unlock();
        }

    }

    @Override
    @Transactional
    public RefundRecordVo queryRefundTrading(RefundRecordVo refundRecordVo) throws ProjectException {
        return commonPayAdapter.queryRefundTrading(refundRecordVo);
    }

    @Override
    public TradingVo closeTrading(TradingVo tradingVo) {
        return commonPayAdapter.closeTrading(tradingVo);
    }

    @Override
    public TradingVo downLoadBill(TradingVo tradingVo) {
        return commonPayAdapter.downLoadBill(tradingVo);
    }
}
